package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.QueryException;
import com.mrd.exception.SaveException;
import com.mrd.gtimp.business.entity.FundAccount;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

/**
 * Created by dark on 17/4/9.
 */
@Service
public class FundAccountBiz extends BaseBiz<FundAccount> {

    @Resource
    @Qualifier("fundAccountDao")
    @Override
    public void setBaseRepository(BaseRepository<FundAccount, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

    /**
     * 初始化账号
     */
    public void initFundAccount(String companyId) throws SaveException {
        FundAccount fundAccount = new FundAccount();
        fundAccount.setId(null);
        fundAccount.setComId(companyId);
        fundAccount.setBalance(0);
        fundAccount.setHoldAmount(0);
        fundAccount.setRegDate(new Date());
        fundAccount.setLastUpdDate(new Date());
        super.saveOrupdateEntity(fundAccount);
    }

    /**
     * 根据公司id查找账户余额
     *
     * @param companyId 公司ID
     */
    public String findBalanceByCompanyId(String companyId) throws QueryException {
        if (StringUtils.isEmpty(companyId)) {
            return null;
        }
        String hql = "select FundAccount.balance from com.mrd.gtimp.business.entity.FundAccount FundAccount where FundAccount.comId='" + companyId + "' order by FundAccount.regDate desc";
        List<Object> list = this.findObjectByHql(hql, 0, 0, null);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0).toString();
        }
        return null;
    }

}
